package com.example.firstdemo.network.service

import com.example.firstdemo.network.api.user.LoginRequest
import com.example.firstdemo.network.api.user.UserApi
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.asSharedFlow

// 用户认证管理类
object AuthManager {

    suspend fun login(username: String, password: String) {
        val resToken = UserApi.login(LoginRequest(username, password))
        resToken.token?.let { UserManager.saveToken(it) }
        val userRes = UserApi.getInfo()
        userRes.user.let { UserManager.saveUserInfo(it) }
    }

    // 登出方法
    suspend fun logout() {
        UserManager.clear()
    }
}

object AuthEventManager {
    private val _authEvents = MutableSharedFlow<AuthEvent>()
    val authEvents: SharedFlow<AuthEvent> = _authEvents.asSharedFlow()

    suspend fun emitEvent(event: AuthEvent) {
        _authEvents.emit(event)
    }

    sealed class AuthEvent {
        object TokenExpired : AuthEvent()
        object Logout : AuthEvent()
    }
}